package com.sks.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.sks.bean.pojo.Users;
import com.sks.utils.StringUtil;
import com.sks.utils.WebUtil;

public class ExternalFilter implements Filter {
   
   private String excludeUrlPattern;

   @Override
   public void destroy() {

   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response,
         FilterChain chain) throws IOException, ServletException {
      HttpServletRequest req = (HttpServletRequest) request;
      
      if (null != excludeUrlPattern) {
         String[] patterns = excludeUrlPattern.split(",");
         String uri = req.getRequestURI();
         for (String pattern : patterns) {
            if (StringUtil.matchURLByTomcat(pattern, uri)) {
               chain.doFilter(request, response);
            }
         }
      }
      
      Users user = WebUtil.getUsers(req);
      if (user == null) {// 如果用户未登录，重定向到用户登陆界面
         String url = WebUtil.getRequestURIWithParam(req);//得到当前请求路径
         String directUrl = new String(Base64.encodeBase64(url.getBytes()));
         HttpServletResponse res = (HttpServletResponse) response;
         
         res.sendRedirect("/sks/privilege/users/logon.do?directUrl=" + directUrl);
      } else {
         chain.doFilter(request, response);
      }
   }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {

   }

   public String getExcludeUrlPattern() {
      return excludeUrlPattern;
   }

   public void setExcludeUrlPattern(String excludeUrlPattern) {
      this.excludeUrlPattern = excludeUrlPattern;
   }
}
